package com.sinosoft.web.easyui.api;

import com.sinosoft.hydra.um.helper.LoggerHelper;
import com.sinosoft.hydra.um.services.FileService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

/**
 * 备份与恢复api
 */
@Controller
@RequestMapping("api/bak")
public class SysBakApi {

    @Autowired
    private FileService fileService;

    /**
     * 页面跳转
     *
     * @return 跳转制定也
     */
    @RequestMapping("index")
    @RequiresPermissions("db:data:list")
    public String index() {
        LoggerHelper.logInfo("访问了数据备份列表页");
        return "hydra_easyui/bak/index";
    }

    /**
     * 页面跳转
     *
     * @return 跳转制定也
     */
    @RequestMapping("bakFiles")
    @ResponseBody
    public Object bakFiles() {
        return fileService.listBak();
    }

    /**
     * 执行删除备份
     *
     * @return 跳转制定也
     */
    @RequestMapping(value = "delBak", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("db:data:delete")
    public Object delBak(@RequestParam(value = "bakName", required = true) String bakName) {
        fileService.delBak(bakName);
        LoggerHelper.logInfo("删除了备份文件{}", bakName);
        return Collections.singletonMap("bakName", bakName);
    }

    /**
     * 执行文件备份
     *
     * @return 跳转制定也
     */
    @RequestMapping(value = "bakUp")
    @RequiresPermissions("db:data:bakup")
    public String bakUp(HttpServletRequest request, Model model) {
        String name = fileService.bakup();
        LoggerHelper.logInfo("进行问数据的备份，生成备份文件{}", name);
        model.addAttribute("d", "bak");
        return "redirect:" + request.getContextPath() + "/app/api/home/redirectWait";
    }

    /**
     * 执行文件备份
     *
     * @return 跳转制定也
     */
    @RequestMapping(value = "recoveryUp")
    @RequiresPermissions("db:data:recovery")
    public String recoveryUp(HttpServletRequest request, Model model,
                             @RequestParam(value = "bakName", required = true) String bakName) {
        fileService.recovery(bakName);
        LoggerHelper.logInfo("使用备份数据{}进行了数据恢复", bakName);
        model.addAttribute("d", "recovery");
        return "redirect:" + request.getContextPath() + "/app/api/home/redirectWait";
    }
}
